from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.utils import timezone
from datetime import timedelta
from management.initialization import DataInitializer
from management.middleware import UserActivityMiddleware, skip_middleware_user_activity
from memento.models import UserStateMemento
from utils.logging_utils import log_request_response
from .models import PendingUser, UserProfile
from .serializers import UserRegisterSerializer, UserLoginSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.authentication import JWTAuthentication
from management.tasks import UserDataTasks
from rest_framework.parsers import MultiPartParser
from django.core.files.images import get_image_dimensions
from django.conf import settings
import uuid
# 注册视图
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
import logging


@api_view(['POST'])
@skip_middleware_user_activity
@log_request_response
def register_user(request):
    # 清理过期的 PendingUser
    PendingUser.cleanup_expired()

    email = request.data.get('email')
    if User.objects.filter(email=email).exists():
        return Response({"error": "This email is already registered."}, status=status.HTTP_400_BAD_REQUEST)

    serializer = UserRegisterSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        # 注册成功后，返回 requires_verification 字段以便前端处理
        return Response({
            "message": "Registration successful. Please verify your email.",
            "requires_verification": True  # 提示前端需要验证码验证
        }, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 用户验证
@api_view(['POST'])
@skip_middleware_user_activity
@log_request_response
def verify_email(request):
    email = request.data.get('email')
    code = request.data.get('code')
    username = request.data.get('username')

    try:
        pending_user = PendingUser.objects.get(email=email, username=username, verification_code=code)

        # 检查是否已超时
        if pending_user.is_expired():
            pending_user.delete()
            return Response({"error": "Verification code expired. Please register again."},
                            status=status.HTTP_400_BAD_REQUEST)

        # 检查用户名是否已被其他已验证用户使用
        if User.objects.filter(username=pending_user.username).exists():
            pending_user.delete()
            return Response({"error": "This username has already been taken by another verified user."},
                            status=status.HTTP_400_BAD_REQUEST)

        # 验证成功，创建正式用户，将哈希密码迁移
        user = User.objects.create(
            username=pending_user.username,
            email=pending_user.email,
            password=pending_user.password,  # 直接迁移哈希后的密码
        )

        UserProfile.objects.create(user=user, luogu_uid=pending_user.luogu_uid)

        pending_user.delete()
        return Response({"message": "Email verified and account created successfully."}, status=status.HTTP_200_OK)
    except PendingUser.DoesNotExist:
        return Response({"error": "Invalid email, username or verification code."}, status=status.HTTP_400_BAD_REQUEST)


# 用户登录，登录视图中包含更多与数据控制的逻辑
@api_view(['POST'])
@skip_middleware_user_activity
@log_request_response
def login_user(request):
    serializer = UserLoginSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.validated_data['user']
        token = RefreshToken.for_user(user)
        is_first_login = user.last_login is None
        # login_user视图中有关数据清洗任务的提交逻辑已被删除
        user.last_login = timezone.now()
        user.save()

        # 调用 UserActivityMiddleware 的静态方法以触发用户活动逻辑
        UserActivityMiddleware.trigger_user_activity(user.id)

        return Response({
            "message": "Login successful.",
            "username": user.username,
            "first_login": is_first_login,
            "refresh_token": str(token),
            "access_token": str(token.access_token),
        }, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 登出视图，不知道有什么用
@api_view(['POST'])
@skip_middleware_user_activity
@log_request_response
def logout_user(request):
    return Response({"message": "Logout successful."}, status=status.HTTP_200_OK)


# 个人信息
@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def self_information(request):

    current_user = request.user
    try:
        user_profile = UserProfile.objects.get(user=current_user)
        return Response({
            "username": current_user.username,
            "email": current_user.email,
            "luogu_uid": user_profile.luogu_uid,
        }, status=status.HTTP_200_OK)
    except UserProfile.DoesNotExist:
        return Response({"error": "User profile not found."}, status=status.HTTP_404_NOT_FOUND)


# 换绑luogu_uid
@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def bind_luogu_uid(request):
    luogu_uid = request.data.get('luogu_uid')
    if not luogu_uid:
        return Response({"error": "Missing 'luogu_uid' in request."}, status=status.HTTP_400_BAD_REQUEST)

    # 检查 luogu_uid 是否为纯数字
    if not luogu_uid.isdigit():
        return Response({"error": "Luogu UID must be a numeric string."}, status=status.HTTP_400_BAD_REQUEST)

    # 获取当前用户
    current_user = request.user
    try:
        user_profile = UserProfile.objects.get(user=current_user)
        user_profile.luogu_uid = luogu_uid  # 绑定新的 Luogu UID
        user_profile.save()

        # 数据初始化
        # 递归任务函数入队仅由中间件模块负责
        UserDataTasks.submit_or_replace_task(current_user.id, UserDataTasks.async_initialize_user_data)

        return Response({"message": "Luogu UID successfully bound."}, status=status.HTTP_200_OK)
    except UserProfile.DoesNotExist:
        UserProfile.objects.create(user=current_user, luogu_uid=luogu_uid)
        return Response({"error": "User profile not found, created profile for you."}, status=status.HTTP_404_NOT_FOUND)


MAX_AVATAR_SIZE_MB = 10  # 最大头像大小限制为10MB


from django.core.files.storage import default_storage


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def upload_avatar(request):
    user_profile = request.user.userprofile
    file = request.FILES.get('avatar')

    if not file:
        return Response({"error": "请上传头像文件。"}, status=400)

    # 检查文件大小
    if file.size > MAX_AVATAR_SIZE_MB * 1024 * 1024:
        return Response({"error": f"文件大小不能超过 {MAX_AVATAR_SIZE_MB}MB。"}, status=400)

    # 检查文件类型
    try:
        width, height = get_image_dimensions(file)
    except Exception:
        return Response({"error": "文件格式不正确，请上传图片文件。"}, status=400)

    # 删除旧头像文件
    if user_profile.avatar and default_storage.exists(user_profile.avatar.path):
        default_storage.delete(user_profile.avatar.path)

    # 更新用户头像
    new_avatar_name = f"{uuid.uuid4().hex}.jpg"
    user_profile.avatar.save(new_avatar_name, file, save=True)

    # 返回完整的头像 URL
    full_avatar_url = request.build_absolute_uri(user_profile.avatar_url)
    return Response({"message": "头像上传成功", "avatar_url": full_avatar_url}, status=200)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_avatar(request):
    user_profile = request.user.userprofile

    # 获取完整的 avatar URL，如果用户没有上传头像则使用默认头像
    # build_absolute_uri
    full_avatar_url = request.build_absolute_uri(user_profile.avatar_url)
    return Response({"avatar_url": full_avatar_url}, status=200)


@api_view(['DELETE'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def delete_avatar(request):
    user_profile = request.user.userprofile

    # 检查用户是否有自定义头像
    if user_profile.avatar and default_storage.exists(user_profile.avatar.path):
        # 删除用户自定义头像文件
        default_storage.delete(user_profile.avatar.path)
        user_profile.avatar = None
        user_profile.save()

        return Response({"message": "头像已成功删除，默认头像将被使用"}, status=200)
    else:
        return Response({"error": "用户未设置自定义头像"}, status=400)
